﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Mail.MiniProgram.Core.Security
{
    public static class AES
    {
        public static string Encrypt(this string data,string key, string iv)
        {
            var rgbKey = Convert.FromBase64String(key);
            var rgbIV = Convert.FromBase64String(iv);
            var bytes = Encoding.UTF8.GetBytes(data);

            try
            {
                using var managed = new AesManaged()
                {
                    Mode = CipherMode.CBC,
                    BlockSize = 128,
                    Padding = PaddingMode.PKCS7
                };
                using var encryptor = managed.CreateEncryptor(rgbKey, rgbIV);
                var final = encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
                return Convert.ToBase64String(final);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        public static string Decrypt(this string data,string key, string iv)
        {
            var rgbKey = Convert.FromBase64String(key);
            var rgbIV = Convert.FromBase64String(iv);
            var bytes = Convert.FromBase64String(data);

            try
            {
                using var managed = new AesManaged()
                {
                    Mode = CipherMode.CBC,
                    BlockSize = 128,
                    Padding = PaddingMode.PKCS7
                };
                using var decryptor = managed.CreateDecryptor(rgbKey, rgbIV);
                var final = decryptor.TransformFinalBlock(bytes, 0, bytes.Length);
                return Encoding.UTF8.GetString(final);
            }
            catch
            {
                return null;
            }
        }
    }
}
